<template>
    <div class="teaching-analysis-container">
      <a-card title="教学分析" :bordered="false">
        <div class="filter-section">
          <a-select
            v-model:value="selectedStudent"
            style="width: 200px"
            placeholder="选择学生"
            allowClear
            @change="handleStudentChange"
          >
            <a-select-option v-for="student in studentOptions" :key="student.id" :value="student.id">
              {{ student.name }}
            </a-select-option>
          </a-select>
          <a-range-picker v-model:value="dateRange" @change="handleDateChange" />
        </div>
        
        <div class="chart-container">
          <div ref="chartRef" style="width: 100%; height: 400px;"></div>
        </div>
      </a-card>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { useUserStore } from '/@/store';
  import * as echarts from 'echarts';
  import { LineChartOutlined } from '@ant-design/icons-vue';
  import { getTeachingStudents, getTeachingAnalysisData } from '/@/api/homework';
  import { message } from 'ant-design-vue';
  import { get } from '/@/utils/http/axios';
  
  const userStore = useUserStore();
  const chartRef = ref<HTMLElement>();
  let chartInstance: echarts.ECharts | null = null;
  
  // 数据状态
  const studentOptions = ref<{id: number, name: string}[]>([]);
  const selectedStudent = ref<number | undefined>(undefined);
  const dateRange = ref<any>(null);
  const chartData = ref<any>({});
  
  // 初始化图表
  const initChart = () => {
    if (!chartRef.value) return;
    
    chartInstance = echarts.init(chartRef.value);
    
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          const date = params[0].axisValue;
          const scores = params.map((item: any) => {
            return `${item.seriesName}: ${item.value[1]}`;
          }).join('<br/>');
          return `${date}<br/>${scores}`;
        }
      },
      legend: {
        data: [] as string[]
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [] as string[]
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value} 分'
        }
      },
      series: [] as any[]
    };
    
    chartInstance.setOption(option);
  };
  
  // 更新图表数据
  const updateChart = () => {
    if (!chartInstance) return;
    
    // 提取所有日期并去重排序
    const allDates = new Set<string>();
    const seriesData: any[] = [];
    
    Object.keys(chartData.value).forEach(key => {
      const studentId = key.replace('student_', '');
      const studentName = studentOptions.value.find(s => s.id === Number(studentId))?.name || `学生 ${studentId}`;
      const dataPoints = chartData.value[key];
      
      const scores = dataPoints.map((point: any) => {
        const date = new Date(point.time);
        const dateStr = `${date.getMonth()+1}/${date.getDate()}`;
        allDates.add(dateStr);
        return [dateStr, point.score];
      });
      
      seriesData.push({
        name: studentName,
        type: 'line',
        data: scores,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: getRandomColor()
        }
      });
    });
    
    const dates = Array.from(allDates).sort((a, b) => {
      const [aMonth, aDay] = a.split('/').map(Number);
      const [bMonth, bDay] = b.split('/').map(Number);
      return aMonth - bMonth || aDay - bDay;
    });
    
    const option = {
      legend: {
        data: seriesData.map(s => s.name)
      },
      xAxis: {
        data: dates
      },
      series: seriesData
    };
    
    chartInstance.setOption(option);
  };
  
  // 获取随机颜色
  const getRandomColor = () => {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  };
  
  // 获取学生列表
  const fetchStudents = async () => {
    try {
      const response = await getTeachingStudents(userStore.user_id);
      studentOptions.value = response.map((id: number) => ({
        id,
        name: `学生 ${id}`
      }));
    } catch (error) {
      message.error('获取学生列表失败');
      console.error(error);
    }
  };
  
  // 获取分析数据
  const fetchAnalysisData = async () => {
    try {
      const response = await getTeachingAnalysisData(
        userStore.user_id,
        selectedStudent.value
      );
      chartData.value = response;
      updateChart();
    } catch (error) {
      message.error('获取分析数据失败');
      console.error(error);
    }
  };
  
  // 学生选择变化
  const handleStudentChange = (value: number | undefined) => {
    selectedStudent.value = value;
    fetchAnalysisData();
  };
  
  // 日期范围变化
  const handleDateChange = () => {
    fetchAnalysisData();
  };
  
  // 初始化
  onMounted(async () => {
    initChart();
    await fetchStudents();
    await fetchAnalysisData();
    
    // 响应式调整图表大小
    window.addEventListener('resize', () => {
      chartInstance?.resize();
    });
  });
  </script>
  
  <style scoped>
  .teaching-analysis-container {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
  }
  
  .filter-section {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
  }
  
  .chart-container {
    margin-top: 20px;
  }
  </style>